/**
 * 权限管理工具类
 */
class AuthManager {
    constructor() {
        this.currentUser = null;
        this.authToken = null;
        this.userMenus = [];
        this.userPermissions = [];
        this.init();
    }

    // 初始化权限管理器
    init() {
        this.loadFromStorage();
    }

    // 从localStorage加载权限信息
    loadFromStorage() {
        try {
            const userStr = localStorage.getItem('currentUser');
            const token = localStorage.getItem('authToken');
            const menusStr = localStorage.getItem('userMenus');
            const permissionsStr = localStorage.getItem('userPermissions');

            if (userStr) this.currentUser = JSON.parse(userStr);
            if (token) this.authToken = token;
            if (menusStr) this.userMenus = JSON.parse(menusStr);
            if (permissionsStr) this.userPermissions = JSON.parse(permissionsStr);
        } catch (error) {
            console.error('加载权限信息失败:', error);
            this.clearAuth();
        }
    }

    // 检查是否已登录
    isLoggedIn() {
        // 重新从localStorage获取最新状态
        const savedUser = localStorage.getItem('currentUser');
        const savedToken = localStorage.getItem('authToken');
        
        if (savedUser && savedToken) {
            try {
                this.currentUser = JSON.parse(savedUser);
                this.authToken = savedToken;
                return true;
            } catch (e) {
                console.error('解析登录信息失败:', e);
                this.clearAuth();
                return false;
            }
        }
        return false;
    }

    // 检查是否有指定权限
    hasPermission(permission) {
        if (!this.userPermissions) return false;
        return this.userPermissions.includes(permission);
    }

    // 检查是否有指定角色
    hasRole(role) {
        if (!this.currentUser) return false;
        return this.currentUser.role === role;
    }

    // 获取用户信息
    getCurrentUser() {
        return this.currentUser;
    }

    // 获取用户菜单
    getUserMenus() {
        return this.userMenus || [];
    }

    // 获取用户权限
    getUserPermissions() {
        return this.userPermissions || [];
    }

    // 获取认证token
    getAuthToken() {
        return this.authToken;
    }

    // 清除认证信息
    clearAuth() {
        this.currentUser = null;
        this.authToken = null;
        this.userMenus = [];
        this.userPermissions = [];
        
        localStorage.removeItem('currentUser');
        localStorage.removeItem('authToken');
        localStorage.removeItem('userMenus');
        localStorage.removeItem('userPermissions');
    }

    // 退出登录
    logout() {
        this.clearAuth();
        window.location.href = 'login.html';
    }

    // 检查登录状态，如果未登录则跳转到登录页
    requireAuth() {
        console.log('执行权限检查...');
        const isLoggedIn = this.isLoggedIn();
        console.log('登录状态:', isLoggedIn);
        
        if (!isLoggedIn) {
            console.log('未登录，跳转到登录页');
            // 添加延迟避免循环跳转
            setTimeout(() => {
                window.location.href = 'login.html';
            }, 100);
            return false;
        }
        console.log('已登录，继续执行');
        return true;
    }

    // 生成侧边栏菜单HTML
    generateSidebarMenu() {
        const currentUser = this.getCurrentUser();
        if (!currentUser) {
            return '<li><a href="#" class="nav-link"><i class="fas fa-info-circle"></i><span>请先登录</span></a></li>';
        }

        // 根据用户角色生成菜单
        const menus = this.getMenusByRole(currentUser.role);
        const currentPage = window.location.pathname.split('/').pop() || 'dashboard.html';

        return menus.map(menu => {
            const isActive = currentPage === menu.url ? 'active' : '';
            return `
                <li>
                    <a href="${menu.url}" class="nav-link ${isActive}">
                        <i class="${menu.icon}"></i>
                        <span>${menu.name}</span>
                    </a>
                </li>
            `;
        }).join('');
    }

    // 根据角色获取菜单
    getMenusByRole(role) {
        const allMenus = [
            { name: '仪表板', url: 'dashboard.html', icon: 'fas fa-tachometer-alt', roles: ['system_admin', 'book_admin', 'normal_user'] },
            { name: '我的借阅', url: 'my-borrows.html', icon: 'fas fa-book-reader', roles: ['normal_user'] },
            { name: '我的费用', url: 'my-payments.html', icon: 'fas fa-wallet', roles: ['normal_user'] },
            { name: '用户管理', url: 'users.html', icon: 'fas fa-users', roles: ['system_admin'] },
            { name: '图书管理', url: 'books.html', icon: 'fas fa-book', roles: ['system_admin', 'book_admin'] },
            { name: '分类管理', url: 'categories.html', icon: 'fas fa-tags', roles: ['system_admin', 'book_admin'] },
            { name: '借阅管理', url: 'borrows.html', icon: 'fas fa-exchange-alt', roles: ['system_admin', 'book_admin'] },
            { name: '财务管理', url: 'payments.html', icon: 'fas fa-credit-card', roles: ['system_admin', 'book_admin'] },
            { name: '通知管理', url: 'notifications.html', icon: 'fas fa-bell', roles: ['system_admin', 'book_admin'] },
            { name: '数据管理', url: 'backup.html', icon: 'fas fa-database', roles: ['system_admin'] },
            { name: '系统配置', url: 'system.html', icon: 'fas fa-cog', roles: ['system_admin'] }
        ];

        return allMenus.filter(menu => menu.roles.includes(role));
    }

    // 根据权限显示/隐藏元素
    applyPermissionControl() {
        // 查找所有带有data-permission属性的元素
        const elements = document.querySelectorAll('[data-permission]');
        elements.forEach(element => {
            const requiredPermission = element.getAttribute('data-permission');
            if (!this.hasPermission(requiredPermission)) {
                element.style.display = 'none';
            }
        });

        // 查找所有带有data-role属性的元素
        const roleElements = document.querySelectorAll('[data-role]');
        roleElements.forEach(element => {
            const requiredRole = element.getAttribute('data-role');
            if (!this.hasRole(requiredRole)) {
                element.style.display = 'none';
            }
        });
    }

    // 获取角色显示名称
    getRoleDisplayName(role) {
        const roleMap = {
            'system_admin': '系统管理员',
            'book_admin': '图书管理员',
            'normal_user': '普通用户'
        };
        return roleMap[role] || role;
    }
}

// 创建全局权限管理器实例
const authManager = new AuthManager();

// 导出到全局作用域
window.AuthManager = AuthManager;
window.authManager = authManager;